<?php

require_once(dirname(__DIR__) . '/api/DB.php');
require_once(dirname(__DIR__) . '/api/response.php');
require_once(dirname(__DIR__) . '/api/func.php');

$_PUT = [];
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    $putData = file_get_contents('php://input');
    parse_str($putData, $_PUT);
}

try {

    $db = new DB();
    $pdo = $db::$pdo;

    foreach (['user_id', 'avatar'] as $value) {
        if (!isset($_PUT[$value])) {
            throw new Exception(fieldMap($value) . '为必传项');
        }

        if (empty($_PUT[$value])) {
            throw new Exception(fieldMap($value) . '不能为空');
        }

        if ($value === 'avatar') {
            // 验证是否为正确的 URL 格式
            if (!filter_var($_PUT['avatar'], FILTER_VALIDATE_URL)) {
                throw new Exception('头像地址不是正确的URL格式');
            }

            // 解析 URL 并验证协议
            $parseUrl = parse_url($_PUT['avatar']);
            if ($parseUrl === false || !$parseUrl['scheme']) {
                throw new Exception('无法解析头像URL');
            }

            // 验证需要是否为 http 或 https
            if (!in_array($parseUrl['scheme'], ['http', 'https'])) {
                throw new Exception('只支持HTTP或HTTPS协议的地址图片');
            }
        }

    }

    // 判断用户是否存在
    $sql = 'select * from users where id = ?';
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$_PUT['user_id']]);
    $res = $stmt->fetch(PDO::FETCH_ASSOC);
    if (empty($res)) {
        throw new Exception('用户不存在，无法修改头像');
    }

    // 判断是否已经有头像，有则删除
    $baseURL = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'];
    $avatarUrl = dirname(__DIR__) . str_replace($baseURL, '', $res['avatar']);
    if (file_exists($avatarUrl)) {
        unlink($avatarUrl);
    }

    // 修改头像
    $sql = 'update users set avatar = ? where id = ?';
    $stmt = $pdo->prepare($sql);
    $res = $stmt->execute([$_PUT['avatar'], $_PUT['user_id']]);
    if (empty($res)) {
        throw new Exception('修改失败');
    }

    myResponse('', 1, 200);
} catch (Exception $e) {
    myResponse($e->getMessage(), 0, 200);
}
